package cn.doitedu.vueapi.controller.user;


import cn.doitedu.vueapi.pojo.tg.Result;
import cn.doitedu.vueapi.pojo.tg.AdUser;
import cn.doitedu.vueapi.service.tg.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

@RestController
public class UserController {

    @Autowired
    UserServiceImpl userService;
    /**
     * 登录
     * @param user
     * @return
     */
    @CrossOrigin
    @PostMapping(value = "/login")
    public Result<AdUser> login(@RequestBody AdUser user) {
        System.out.println("收到登录请求...................");
        System.out.println(user.getName() + "  :   " + user.getPassword());

        // 对 html 标签进行转义，防止 XSS 攻击
        String username = HtmlUtils.htmlEscape(user.getName());
        user.setName(username);

        AdUser login = userService.login(user);
        if(login !=null){
            return new Result(200,login,"ok");
        }

        return new Result(400,null,"用户名或密码不正确");
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @CrossOrigin
    @PostMapping(value = "/register")
    public Result<AdUser> register(@RequestBody AdUser user){
        String username = HtmlUtils.htmlEscape(user.getName());
        user.setName(username);


        AdUser u = new AdUser();
        u.setName(user.getName());

        boolean exist = userService.exist(u)!=null;
        if(exist){
            return new Result(400,null,"用户名已存在");
        }

        AdUser register = userService.register(user);
        if(register != null){
            AdUser resU = userService.exist(u);
            return new Result(200,resU,"ok");
        }

        return new Result(400,null,"注册失败");
    }



}
